import request from "/utils/omsRequest";
import validator from "/utils/validators";
import { showToast } from "/utils/common";
import { bus } from "/utils/core";
import { contractType } from "/utils/dictionary";
const app = getApp();
const contractTypes = [];
for (const i in contractType) {
  contractTypes.push({
    value: i,
    label: contractType[i]
  })
}

Page({
  data: {
    userInfo: null,
    info: null,
    products: [],
    productMap: {},
    services: [],
    orgList: [],
    dingUserList: [],
    dingOrgIndex: null,
    dingUserIndex: null,
    contractTypeIndex: null,
    contractTypes,
    form: {
      contractType: null,
      contractList: [],
      freeServiceList: [],
      buyServiceList: [],
      depositList: [],
      saleDingOrgId: null,
      saleDingUserId: null,
      sysEnclosureList: []
    }
  },
  onUnload() {
    bus.remove("contractFile")
  },
  onLoad(query) {
    this.setData({
      userInfo: app.globalData.userInfo,
      "form.sysEnclosureList": []
    });
    request({
      url: "/ajax/merchant/findMerchant",
      data: {
        id: query.id
      }
    }).then(res => {
      this.setData({
        info: res.vo,
        "form.merchantId": res.vo.id,
        "form.merchantNumber": res.vo.merchantNumber
      });
    });
    request({
      url: "/ajax/product/list"
    }).then(res => {
      let productMap = {};
      res.voList.forEach(product => {
        productMap[product.id] = product.name
      });
      this.setData({
        products: res.voList,
        productMap: productMap
      });
    });
    request({
      url: "/ajax/freeService/list"
    }).then(res => {
      this.setData({
        services: res.voList
      });
    });
    request({
      url: "/ajax/user/org",
      data: {
        departmentId: 113682313
      }
    }).then(async (res) => {
      this.setData({
        orgList: res.voList
      })
      // 默认选中登陆者销售用户
      let dingOrgIndex = res.voList.findIndex(item => item.id === +this.data.userInfo.dingOrgId);
      if (dingOrgIndex >= 0) {
        await this.onDingOrgChange({ detail: { value: dingOrgIndex } });
        let dingUserIndex = this.data.dingUserList.findIndex(item => item.userid === this.data.userInfo.dingUserId);
        this.onDingUserChange({ detail: { value: dingUserIndex } })
      }
    });
    bus.subscribe("contractFile", (files) => {
      if (files.length > 0) {
        this.data.form.sysEnclosureList.push(...files);
        this.setData({
          form: this.data.form
        });
      }
    })
  },
  // 合同类型change
  onContractTypeChange(e) {
    this.setData({
      contractTypeIndex: e.detail.value,
      "form.contractType": this.data.contractTypes[e.detail.value].value
    })
  },
  // 产品增删改 (同步收款记录)
  onProductChange(obj) {
    if (obj.index === null && obj.form) {
      // new
      if (obj.form.productId === 22) {
        this.setData({
          "form.buyServiceList": obj.buyServiceList
        })
      }
      this.data.form.contractList.push(obj.form);
    }
    if (obj.index !== null && obj.form) {
      // update
      if (obj.form.productId === 22) {
        this.setData({
          "form.buyServiceList": obj.buyServiceList
        })
      }
      this.data.form.contractList.splice(obj.index, 1, obj.form);
      this.syncDepositList()
    }
    if (obj.index !== null && !obj.form) {
      // remove
      if (this.data.form.contractList[obj.index].productId === 22) {
        this.setData({
          "form.buyServiceList": []
        })
      }
      this.data.form.contractList.splice(obj.index, 1);
      this.syncDepositList()
    }
    this.setData({
      "form.contractList": this.data.form.contractList
    });
  },
  // 所属机构change
  async onDingOrgChange(e) {
    this.setData({
      dingOrgIndex: this.data.orgList.length > 0 ? e.detail.value : null,
      "form.saleDingOrgId": this.data.orgList.length > 0 ? this.data.orgList[e.detail.value].id : null,
      dingUserIndex: null,
      "form.saleDingUserId": null
    })
    await request({
      url: "/ajax/user/dingUser",
      data: {
        departmentId: this.data.orgList[e.detail.value].id
      }
    }).then(res => {
      this.setData({
        dingUserList: res.voList
      })
    })
  },
  // 所属销售change
  onDingUserChange(e) {
    this.setData({
      dingUserIndex: this.data.dingUserList.length > 0 ? e.detail.value : null,
      "form.saleDingUserId": this.data.dingUserList.length > 0 ? this.data.dingUserList[e.detail.value].userid : null
    })
  },
  // 赠送增值服务增删改
  onServiceChange(obj) {
    if (obj.index === null && obj.form) {
      this.data.form.freeServiceList.push(obj.form);
    } else if (obj.index !== null && obj.form) {
      this.data.form.freeServiceList.splice(obj.index, 1, obj.form);
    } else if (obj.index !== null && !obj.form) {
      this.data.form.freeServiceList.splice(obj.index, 1);
    }
    this.setData({
      "form.freeServiceList": this.data.form.freeServiceList
    });
  },
  // 购买增值服务增删改
  onBuyServiceChange(obj) {
    if (obj.index === null && obj.form) {
      this.data.form.buyServiceList.push(obj.form)
    } else if (obj.index !== null && obj.form) {
      this.data.form.buyServiceList.splice(obj.index, 1, obj.form)
    } else if (obj.index !== null && !obj.form) {
      this.data.form.buyServiceList.splice(obj.index, 1)
    }
    this.setData({
      "form.buyServiceList": this.data.form.buyServiceList
    })
  },
  // 收款记录增删改
  onDepositChange(obj) {
    if (obj.index === null && obj.form) {
      this.data.form.depositList.push(obj.form)
    } else if (obj.index !== null && obj.form) {
      this.data.form.depositList.splice(obj.index, 1, obj.form)
    } else if (obj.index !== null && !obj.form) {
      this.data.form.depositList.splice(obj.index, 1)
    }
    this.setData({
      "form.depositList": this.data.form.depositList
    })
  },
  // 同步收款记录
  syncDepositList() {
    for (let i = 0; i < this.data.form.depositList.length; i++) {
      let filteredData = this.data.form.contractList.find(item => item.productId === this.data.form.depositList[i].productId);
      if (!filteredData) {
        this.data.form.depositList.splice(i, 1);
        i--;
      }
    }
    this.setData({
      "form.depositList": this.data.form.depositList
    })
  },
  // 删除合同附件
  onRemoveFile(e) {
    this.data.form.sysEnclosureList.splice(e.target.dataset.index, 1);
    this.setData({
      form: this.data.form
    });
  },
  // 提交
  onSubmit() {
    let validate = new validator();
    validate.add("checkEmpty", this.data.form.contractType, "请选择合同类型");
    validate.add("checkEmptyArray", this.data.form.contractList, "请至少添加一个产品");
    if (this.data.form.contractList.find(item => item.productId === 22)) {
      validate.add("checkEmptyArray", this.data.form.buyServiceList, "增值服务合同，至少添加一条购买增值服务")
    }
    validate.add("checkEmpty", this.data.form.saleDingOrgId, "请选择所属机构");
    validate.add("checkEmpty", this.data.form.saleDingUserId, "请选择所属销售");
    validate.add("checkEmptyArray", this.data.form.depositList, "请上传收款记录");
    validate.add("checkEmptyArray", this.data.form.sysEnclosureList, "请至少添加一个合同附件");
    if (validate.check()) {
      this.data.form.freeServiceAmount = this.data.form.freeServiceList.reduce((pre, cur) => pre + cur.totalPrice, 0)
      let data = JSON.parse(JSON.stringify(this.data.form))
      data.freeServiceList.push(...data.buyServiceList)
      data.contractList.forEach(contract => {
        contract.contractDepositRecordList = data.depositList.filter(
          item => item.productId === contract.productId
        );
      });
      console.log(data)
      dd.showLoading({
        content: '加载中...'
      });
      request({
        url: "/ajax/contract/createContract",
        method: "post",
        data: data,
        headers: {
          "Content-Type": "application/json;utf-8"
        }
      }).then(() => {
        dd.hideLoading();
        showToast({
          type: "success",
          msg: "创建成功!"
        });
        dd.navigateBack()
      })
    }
  }
});
